package com.fly.uaa.security;

import com.fly.uaa.model.CustomerUserDetail;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义CustomerAccessTokenConverter 这个类的作用主要用于AccessToken的转换，
 * 默认使用DefaultAccessTokenConverter 这个装换器
 * DefaultAccessTokenConverter有个UserAuthenticationConverter，这个转换器作用是把用户的信息放入token中，
 * 默认只是放入username
 * 自定义了下这个方法，加入了额外的信息
 *
 * @author: fly
 * @date: 2018/11/26 17:26
 */
public class CustomerAccessTokenConverter extends DefaultAccessTokenConverter {
    public CustomerAccessTokenConverter(CustomUserDetailsService customUserDetailsService) {
        super.setUserTokenConverter(new CustomerUserAuthenticationConverter(customUserDetailsService));
    }

    private class CustomerUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
        private CustomUserDetailsService customUserDetailsService;

        public CustomerUserAuthenticationConverter(CustomUserDetailsService customUserDetailsService) {
            this.customUserDetailsService = customUserDetailsService;
        }

        @Override
        public Map<String, ?> convertUserAuthentication(Authentication authentication) {
            Map<String, Object> response = new LinkedHashMap<>();
            response.put("userId", ((CustomerUserDetail) authentication.getPrincipal()).getUserId());
            if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
                response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
            }
            return response;
        }

        @Override
        public Authentication extractAuthentication(Map<String, ?> map) {
            if (!map.containsKey("userId")) {
                return null;
            }
            long userId = Long.parseLong(map.get("userId").toString());
            Object principal = null;
            Collection<? extends GrantedAuthority> authorities = this.getAuthorities(map);
            if (this.customUserDetailsService != null) {
                UserDetails user = this.customUserDetailsService.loadUserByUserId(userId);
                authorities = user.getAuthorities();
                principal = user;
            }
            return new UsernamePasswordAuthenticationToken(principal, "N/A", authorities);
        }

        private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
            if (!map.containsKey("authorities")) {
                return null;
            }
            Object authorities = map.get("authorities");
            if (authorities instanceof String) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
            } else if (authorities instanceof Collection) {
                return AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.collectionToCommaDelimitedString((Collection) authorities));
            } else {
                throw new IllegalArgumentException("Authorities must be either a String or a Collection");
            }

        }
    }
}
